package com.demo.woziqi.util;


import com.ibatis.common.resources.Resources;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;

/**
 * @Author 宋明松
 * @Version V1.0.0
 * @Date 2022-05-30
 * <p>
 * 数据库操作类
 */
public class DBUtil {
    private static final ThreadLocal<Connection> conns = new ThreadLocal<>();
    private static String driverClassName;
    private static String pwd;
    private static String username;
    private static String url;

    static { // 加载数据库配置文件
        Properties props = null;
        try {
            props = Resources.getResourceAsProperties("jdbc.properties");
        } catch (IOException e) {
            e.printStackTrace();
        }
        driverClassName=props.getProperty("jdbc.driverClassName");
        pwd=props.getProperty("jdbc.password");
        username=props.getProperty("jdbc.username");
        url=props.getProperty("jdbc.url");
    }

    /**
     * 获取数据库连接
     *
     * @return 返回一个数据库连接
     * @throws Exception
     */
    public static Connection getConnection() throws Exception {
       Connection conn = conns.get();
        Class.forName(driverClassName);// 注册驱动
        if (conn==null){
            conn = DriverManager.getConnection(url, username, pwd);// 获取数据库连接对象
            conns.set(conn);
        }
        return conn;
    }
}
